<template>
  <view class="content">
    <!-- <view class="tab_top" :style="{'height':(statusBarTop)+'px'}"></view> -->
    <!-- <uni-nav-bar class="navsbar" left-icon="back" title="充电柜详情" color="#ffffff" backgroundColor="#1977d2"
      @clickLeft="goBack">
    </uni-nav-bar> -->
    <view v-show='advertising' style='width: 100%;'>
      <view class="skip">
        <view @click="hideAdverment">
          跳过
        </view>
      </view>
      <swiper class="swiper" :indicator-dots='false' indicator-color="#fff" indicator-active-color='#ccc'
        :circular='true' :autoplay='true' :interval='3000' :duration='1000'>
        <swiper-item style="height: 100vh;">
          <view class="img">
            <image :src="IMGLink + imgUrl" mode="widthFix"></image>
          </view>
        </swiper-item>
      </swiper>
    </view>

    <view v-show="!advertising" style="padding-bottom: 150rpx;overflow-x: hidden;"
      :class="[{'filterBg':!dataDetail.isOnline || !dataDetail.isEnable}]">
      <view style='width: 100%;height: 150rpx;background-color: #1976d2;'></view>
      <view class="content-view" style='margin-top: -130rpx;margin-bottom: -5px;'>
        <uni-card>
          <view class="networks">
            <text class='site'>{{dataDetail.name}}</text>
            <image v-if="dataDetail.cabinetState.signalIntensity" style="width: 30rpx; height: 30rpx;"
              :src="signalData[dataDetail.cabinetState.signalIntensity]"></image>
            <image v-else style="width: 30rpx; height: 30rpx; position: relative; top: 40rpx;left: 12rpx;"
              src="/static/offLine.png">
            </image>
          </view>

          <view class='address'>设备编号:{{dataDetail.code}}</view>
          <view class='address' style="margin-bottom: 10rpx;">设备地址:{{dataDetail.address || '暂无'}}</view>
          <view class="tags">
            <uni-tag :text="isPrivateDate[dataDetail.isPrivate]" type="success"></uni-tag>
            <!-- 组织内免费，判断当前登录用户所在组织是否和柜子组织一致，一致 显示免费  不一致 收费 -->

            <uni-tag v-if="dataDetail.chargeType == 'FREE_FOR_ORG'"
              :text="(userinfo.organizationId == dataDetail.chargingNetwork.organization.id)? chargeTyleData[dataDetail.chargeType]:'收费'"
              type="success"></uni-tag>
            <uni-tag v-else :text="chargeTyleData[dataDetail.chargeType]" type="success"></uni-tag>

          </view>
          <!-- <view @click="distance" class='card-bottom' style='margin-left: -18px;border-right:2px solid #fff;'>
            <image class='distanceImg' src='../../static/distanceImg.png'></image>
            <text>{{caculateLL(dataDetail.lat,dataDetail.lng,coord.lat,coord.lng) | toFixed}}</text>
          </view> -->
          <view class='card-bottom' @click="enshrine()" style='margin-left: -18px;border-right:2px solid #fff;'>
            <image class='distanceImg'
              :src="isCollection == 1 ? '../../static/enshrine.png' : '../../static/collection.png'"></image>
            <text>收藏</text>
          </view>
          <view class='card-bottom' style='float: right;margin-right: -18px'>
            <image class='distanceImg' src='../../static/customer-service.png'></image>
            <text @click="serve()" style='float: left;color: #656565;font-size: 28rpx;'>联系客服</text>
          </view>
        </uni-card>
      </view>

      <view v-if="dataDetail.cabinetBins && dataDetail.cabinetBins.length>0"
        style='margin:5px 10px 0px 10px;float: left;width: 710rpx;box-shadow: 0px 0px 3px 1px rgba(0, 0, 0, 0.08); border-radius: 15rpx;'>
        <view style='display: flex;flex-wrap:wrap;padding-bottom: 54rpx; background: #fff;border-radius: 15rpx;'>
          <view class='warehouse-view' v-for="(item, index) in dataDetail.cabinetBins" :key='index'>
            <!-- item.doorIsEnable == 1,启用0 未启用 -->
            <view class="state enableClass" v-if="!item.doorIsEnable" @click="skip(item)">禁用</view>
            <view class='state' v-else
              :class="{'state-leisure' : item.status== 0, 'state-inUse' : item.status== 1, 'state-malfunction' : item.status== 2}"
              @click="skip(item)">
              {{statusData[item.status]}}
            </view>
            <text class='state-number'>{{item.binIndex}}号仓</text>
          </view>
        </view>
      </view>
      <!-- </uni-card> -->

      <view class="content-view">
        <uni-card :border="false">
          <view class="title">
            收费组成（电费+服务费+占仓费）
          </view>
          <view class="table">
            <view class="switchHead" v-if="tabShow">
              <view v-for="(item,index) in ['按时','按量']" class="boxList" :class="{'activeCss':activeIndex==index}"
                :key="index" @click="clickTab(index)">
                <text>{{item}}</text>
              </view>
            </view>

            <view class="table-title">
              <view class="time-node" v-if="activeIndex == 0">充电收费</view>
              <view v-else>
                <text class="time-node">收费（kW·h）</text>
                <text class="time-node">
                  <text>电费</text>
                  <text>服务费</text>
                </text>
              </view>
            </view>
            <view class="time">
              <view style='width:100%;'>
                <view v-for="(criterion, criterionIndex) in dataDetail.chargeTmpl.chargeTmplPriceList">
                  <view v-if="activeIndex == 0">
                    <text v-if="criterion.type=='DURATION'"
                      class="time-node">{{criterion.price}}元/{{criterion.unit}}小时</text>
                  </view>
                  <view v-else>
                    <text v-if="criterion.type!='DURATION'" class="time-node">
                      <text>{{criterion.price}}元/kW·h</text>
                      <text>{{criterion.serviceFee}}元/kW·h</text>
                    </text>
                  </view>
                </view>
              </view>
            </view>
          </view>
          <view class="title" style='color: #393939;margin:40rpx 0rpx 20rpx 0rpx;'>
            占仓费用
          </view>
          <view class="info">
            <view>充电完成后，{{dataDetail.chargeTmpl.occupyFreeDuation || 0}}小时内免费。</view>
            <view>
              超出{{dataDetail.chargeTmpl.occupyFreeDuation || 0}}小时，按{{dataDetail.chargeTmpl.occupyChargePrice || 0}}元/{{dataDetail.chargeTmpl.occupyChargeDuration || 0}}小时收费，最高收费{{dataDetail.chargeTmpl.occupyChargeUpperLimit || 0}}元。
            </view>
            <view>免费占仓时段：{{dataDetail.chargeTmpl.occupyFreeStartTime || 0}} -
              {{dataDetail.chargeTmpl.occupyFreeEndTime || 0}}
            </view>
          </view>
          <view class="tips">说明：充电过程中，提前充满、充电器过载引起意外中断、用户主动停止充电等情况支付金额不予退还</view>
        </uni-card>
      </view>
    </view>
  </view>
</template>

<script>
  import {
    chargingCabinet,
    collect
  } from '@/api/equip.js';
  import {
    caculateLL
  } from '@/common/main.js'
  import {
    listAdvertisementsOnMobile
  } from '@/api/login.js'
  import {
    mapState
  } from 'vuex';
  export default {
    data() {
      return {
        IMGLink: this.$url,
        equipid: '', //充电柜id
        code: '', //充电柜编码
        dataDetail: {},

        caculateLL: caculateLL,
        statusData: {
          0: '空闲',
          1: '使用中',
          2: '故障'
        },
        signalData: {
          1: "/static/1.png",
          2: "/static/2.png",
          3: "/static/3.png",
          4: "/static/4.png",
          5: "/static/5.png",
        },
        activeIndex: 0,
        tabShow: false,
        details: {
          data: {
            name: '',
            signal: 0,
            distance: '0',
            address: '',
            leisure: 0,
            sum: 0,
            code: '',
            id: ''
          }

        },
        power: '220',
        lat: '',
        lng: '',
        warehouseList: [

        ],
        isCollection: 0,
        serveData: {},
        option: '',
        costTemplate: [],
        costTemplateElse: {
          explain: '',
          occupyFreeDuration: '',
          occupyChargeDuration: '',
          occupyChargePrice: '',
          occupyChargeUpperLimit: '',
          occupyFreeEndTime: '',
          occupyFreeStartTime: ''
        },
        options: '',
        signalIntensity: '../../static/1.png',
        advertising: false,
        starImg: '',
        address: '',
        imgUrl: '',
        time: null,
        statusBarTop: 0,
        chargeTyleData: {},
        isPrivateDate: {
          '1': "私有柜",
          '0': '共有柜'
        },
      }
    },

    filters: {
      toFixed(str) {
        if (!str) return;
        let count = str > 1000 ? ((str / 1000).toFixed(2) + 'km') : (str.toFixed(2) + 'm');
        return count;
      }
    },
    onLoad(option) {
      // 只在微信小程序内获取改数据
      //#ifdef MP-WEIXIN	
      let menuButtonInfo = uni.getMenuButtonBoundingClientRect();
      this.statusBarTop = menuButtonInfo.top;
      //#endif
      this.code = option.code || '';
      this.equipid = option.equipid || '';

      if (this.equipid) {
        this.collectStatus();
      }

      //微信扫码进 获取广告
      if (option.q) {
        let code = decodeURIComponent(option.q);
        code = code.split('').reverse().join('');
        code = code.substr(0, code.indexOf('/'));
        code = code.split('').reverse().join('');
        this.code = code;
        this.getAdverment();
      }
    },
    computed: {
      ...mapState(['coord', 'userinfo', 'enums'])
    },
    watch: {
      'enums.CHARGING_CABINET_CHARGE_TYPE'(newVal, oldVal) {
        this.chargeTyleData = Object.fromEntries(newVal.map(item => {
          return [item.code, item.label]
        }));
      },
    },
    created() {

    },
    async onShow() {
      await this.getDataList();
    },
    methods: {
      // 返回home页
      // goBack() {
      //   uni.switchTab({
      //     url: '/pages/home/home'
      //   })
      // },
      // 获取广告
      getAdverment() {
        this.advertising = true;
        listAdvertisementsOnMobile('/selectUrl', 'get')
          .then((res) => {
            if (res.data) {
              this.imgUrl = res.data.url;
              this.time = setTimeout(() => {
                this.advertising = false;
              }, res.data.duration * 1000);
            } else {
              this.advertising = false;
            }
          }).catch(err => {
            this.advertising = false;
          })
      },
      hideAdverment() {
        this.advertising = false;
        clearTimeout(this.time);
      },
      getDataList() {
        this.$Toast.loading('加载中~');
        chargingCabinet('/selectAllData', 'get', {
          code: this.code
        }).then(res => {
          if (res.code == 200) {
            uni.hideLoading();

            this.dataDetail = res.data;
            if (!this.dataDetail.isOnline) {
              this.$Toast.none('当前设备未在线，请联系运维人员！');
            } else if (!this.dataDetail.isEnable) {
              this.$Toast.none('当前设备已禁用，请联系运维人员！');
            }
            if (!this.equipid) {
              this.equipid = res.data.id;
              this.collectStatus();
            }
            let durate = this.dataDetail.chargeTmpl.chargeTmplPriceList.filter(item => item.type == 'DURATION' ||
              item.type == '按时');
            let quilty = this.dataDetail.chargeTmpl.chargeTmplPriceList.filter(item => item.type == 'QUANTITY' ||
              item.type == '按量');
            if (durate.length > 0) {
              this.activeIndex = 0;
            } else if (durate.length == 0 && quilty.length > 0) {
              this.activeIndex = 1;
            }
            if (durate.length > 0 && quilty.length > 0) {
              this.tabShow = true;
            }

            // 判断是否是私有柜且组织内免费 当前用户是否在组织内
            if (this.dataDetail.isPrivate == 1 && (this.userinfo
                .organizationId != this.dataDetail.chargingNetwork
                .organization.id)) { //私有柜
              this.$Toast.none('当前为私有柜，不可使用！');
            }

            this.$store.dispatch("updateUserInfo");
            this.$store.dispatch("enums");
            if (!this.coord.lat) {
              this.$store.dispatch("updateCoord");
            }
          } else {
            this.$Toast.none(res.message);
          }
        }).catch(err => {})
      },
      collectStatus() {
        collect('/selectFUserChargingCabinet', 'get', {
          pageNum: 0,
          pageSize: 10,
          lat: this.coord.lat,
          lng: this.coord.lng,
          chargingCabinetId: this.equipid
        }).then(res => {
          let datas = res.data.records;
          this.isCollection = datas.length > 0 ? 1 : 0;
        }).catch(error => {})
      },
      clickTab(index) {
        this.activeIndex = index;
      },
      getState(status) {
        let state = '';
        if (status == 0) {
          state = '空闲';
        } else if (status == 1) {
          state = '使用中';
        } else if (status == 2) {
          state = '故障中';
        }
        return state;
      },
      skip(data) {
        if (!this.dataDetail.isOnline) {
          this.$Toast.none('当前设备未在线，请联系运维人员！');
          return;
        }
        if (!this.dataDetail.isEnable) {
          this.$Toast.none('当前设备已禁用，请联系运维人员！');
          return;
        }
        if (this.dataDetail.isPrivate == 1 && (this.userinfo
            .organizationId != this.dataDetail.chargingNetwork
            .organization.id)) { //私有柜
          this.$Toast.none('当前为私有柜，不可使用！');
          return;
        }
        if (!data.doorIsEnable) {
          this.$Toast.none('仓门禁用，不可使用！');
          return;
        }
        // 0: '空闲',1: '使用中',2: '故障'
        if (data.status == '1') {
          this.$Toast.error('设备使用中');
        } else if (data.status == '2') {
          this.$Toast.error('设备故障中');
        } else {
          uni.navigateTo({
            url: `../chargeCabinetOpt/chargeCabinetOpt?code=${this.code}&binIndex=${data.binIndex}&equipid=${this.equipid}`
          })
        }
      },
      // 收藏
      enshrine() {
        // this.isCollection == 0
        if (Object.keys(this.dataDetail).length == 0) {
          this.$Toast.none('当前设备不存在！');
          return;
        }
        this.$Toast.loading('操作中···');
        let type = this.isCollection == 0 ? 'insert' : 'delete';
        collect(`/insertFUserChargingCabinet?chargingCabinetId=${this.equipid}&type=${type}`, 'post').then(res => {
            if (res.code == 200) {
              this.isCollection = this.isCollection == 0 ? 1 : 0;
              let msg = this.isCollection == 0 ? '取消收藏成功' : '收藏成功';
              this.$Toast.none(msg);
            }
          })
          .catch(err => {

          })
      },
      serve() {
        if (Object.keys(this.dataDetail).length == 0) {
          this.$Toast.none('当前设备不存在！');
          return;
        }
        this.serveData.distance = this.details.data.distance;
        uni.navigateTo({
          url: `../serve/serve?code=${this.code}&lat=${this.coord.lat}&lng=${this.coord.lng}`
        })
      },
      // 导航
      distance() {
        let that = this;
        uni.getLocation({
          type: 'gcj02', //返回可以用于uni.openLocation的经纬度
          success: function(res) {
            const latitude = res.latitude;
            const longitude = res.longitude;
            uni.openLocation({
              latitude: that.dataDetail.lat, //维度
              longitude: that.dataDetail.lng, //经度
              name: that.dataDetail.chargingNetwork.name, //目的地定位名称
              scale: 15, //缩放比例
              address: that.dataDetail.address, //导航详细地址
              success: function() {}
            });
          },
          fail: (err) => {
            if (err.errMsg.indexOf('频繁调用')) {
              uni.showToast({
                title: '请勿频繁调用',
                icon: 'error',
                duration: 1500
              })
            } else {
              uni.showToast({
                title: '请开启定位',
                icon: 'error',
                duration: 1500
              })
            }
          }
        });
      },
      scanCode() {
        uni.scanCode({
          onlyFromCamera: true,
          scanType: 'qrCode',
          success: function(res) {
            let str = res.result;
            let index = str.lastIndexOf('/');
            let code = str.substr(index + 1, str.length);

            uni.redirectTo({
              url: '../rechargeCabinet/rechargeCabinet?code=' + code
            })
          },
          fail: (err) => {
            console.log(err)
          }
        });
      },
      // loadList(res, option) {
      //   this.costTemplate = [];
      //   let that = this;
      //   if (res.data.charge) {
      //     this.costTemplateElse.occupyFreeEndTime = res.data.charge.occupyFreeEndTime ? res.data.charge
      //       .occupyFreeEndTime : '';
      //     this.costTemplateElse.occupyFreeStartTime = res.data.charge.occupyFreeStartTime ? res.data.charge
      //       .occupyFreeStartTime : '';
      //     this.costTemplateElse.occupyFreeDuration = res.data.charge.occupyFreeDuration >= -1 ? res.data.charge
      //       .occupyFreeDuration : '';
      //     this.costTemplateElse.occupyChargeDuration = res.data.charge.occupyChargeDuration >= -1 ? res.data.charge
      //       .occupyChargeDuration : '';
      //     this.costTemplateElse.occupyChargePrice = res.data.charge.occupyChargePrice >= -1 ? res.data.charge
      //       .occupyChargePrice : '';
      //     this.costTemplateElse.occupyChargeUpperLimit = res.data.charge.occupyChargeUpperLimit >= -1 ? res.data.charge
      //       .occupyChargeUpperLimit : '';
      //     if (res.data.charge.chargeIntervalsByTime) {
      //       res.data.charge.chargeIntervalsByTime.forEach(data => {
      //         let dataList = [];
      //         data.chargeIntervalPrices.forEach(value => {
      //           if (value.cost >= -1 && value.unitVolume >= -1) {
      //             dataList.push(value);
      //           }
      //         });
      //         data.chargeIntervalPrices = dataList;
      //         that.costTemplate.push(data);
      //       })
      //     }
      //   }

      //   this.details.data.name = res.data.name ? res.data.name : '';
      //   this.details.data.address = res.data.address ? res.data.address : '';
      //   this.details.data.code = res.data.code ? res.data.code : '';
      //   this.details.data.id = res.data.id;
      //   if (option.distance) {
      //     this.details.data.distance = Number(option.distance).toFixed(2);
      //   }
      //   this.warehouseList = [];
      //   if (res.data.cabinetBins) {
      //     res.data.cabinetBins.forEach(val => {
      //       let data = {
      //         state: this.getState(val.status),
      //         val: val.status,
      //         number: val.binIndex,
      //         id: val.id,
      //         chargeId: res.data.charge.id
      //       }
      //       this.warehouseList.push(data);
      //     })
      //   };
      //   this.isCollection = res.data.isCollection;
      //   this.serveData = res.data.network;
      //   this.serveData.lat = res.data.lat;
      //   this.serveData.lng = res.data.lng;
      // }
    }
  }
</script>
<style lang="scss" scoped>
  @import url('../commonStyle/commonStyle.css');
  @import "@/static/css/common.scss";

  .switchHead {
    border: 1px solid #3672a0;
    border-radius: 10rpx;
    line-height: 60rpx;
    color: #3672a0;
    margin-bottom: 8rpx;
    @include flexLayout(center, space-between);

    view {
      width: 50%;
      text-align: center;
    }

    .activeCss {
      background: #3672a0;
      color: #FFFFFF;
    }
  }

  page {
    background-color: #f7f7f7;
  }

  .content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .navsbar {
      width: 100%;
    }

    .tab_top {
      width: 100%;
      height: 88rpx;
      background: #1977d2;
    }
  }

  .uni-card {
    padding: 0 0px !important;
  }

  .content-view {
    margin: 0px 10px;

    .table {
      width: 100%;
      margin-top: 30upx;

      .table-title {
        display: flex;
        align-items: center;

        view {
          width: 100%;
          text-align: center;
          background-color: #eff8ff;
          color: #3672a0;
        }

        view:nth-child(1) {
          border-radius: 10upx 0 0 0;
        }

        view:nth-child(2) {
          border-radius: 0 10upx 0 0;
        }
      }

      .time {
        display: flex;
        align-items: stretch;

        .time-slot {
          // width: 50%;
          // height: 100%;
          // text-align: center;
          // background-color: #eff8ff;
          // border: 2upx solid #fff;
          width: 50%;
          text-align: center;
          background-color: #eff8ff;
          border: 2rpx solid #fff;
        }

        .fillet1 {
          border-radius: 0 0 0 10upx;
        }

        .fillet2 {
          view:nth-child(2) {
            border-radius: 0 0 10upx 0;
          }
        }
      }
    }
  }

  .time-node {
    display: inline-block;
    width: 100%;
    text-align: center;
    background-color: #eff8ff;
    height: 98upx;
    line-height: 100upx;
    border: 2upx solid #fff;

    text {
      width: 50%;
      display: inline-block;
      height: 98upx;
      line-height: 100upx;
      border: 2upx solid #fff;
      box-sizing: border-box;
    }
  }

  .distanceImg {
    width: 20px;
    height: 20px;
    float: left;
    margin-right: 8px;
  }

  .networks {
    @include flexLayout(center, space-between);
    padding-top: 36rpx;
  }

  .site {
    max-width: 92%;
    font-size: 18px;
    font-weight: 900;
    float: left;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .address {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 100%;
    float: left;
    margin-top: 5px;
    font-size: 26upx;
    color: #858585;
  }

  .card-bottom {
    float: left;
    width: calc(50% + 17px);
    text-align: center;
    background: #ecf6ff;
    height: 30px;
    line-height: 30px;
    margin-top: 15px;
    @include flexLayout(center, center);
  }

  .warehouse {
    float: left;
    // width: calc(100% - 20px);
    background: #fff;
    border-radius: 6px;
    margin-bottom: 20px;
    padding: 0px 10px;
  }

  .warehouse-view {
    width: 105rpx;
    margin-left: 49rpx;
    margin-top: 48rpx;
  }

  .state {
    position: relative;
    float: left;
    border-radius: 100%;
    line-height: 105rpx;
    width: 105rpx;
    text-align: center;
    height: 105rpx;
    border-radius: 105rpx;
    font-size: 26rpx;
    margin-bottom: 25rpx;
  }

  .enableClass {
    border: 2px solid red;
    color: red;
    background:
      linear-gradient(45deg, transparent 49.5%, red 49.5%, red 50.5%, transparent 50.5%);

  }

  .state-leisure {
    border: 2px solid #20B13B;
    color: #20B13B;
  }

  .state-inUse {
    border: 2px solid #FE9201;
    color: #FE9201;
  }

  .state-malfunction {
    border: 2px solid #BEBEBE;
    color: #BEBEBE;
  }

  .state-number {
    float: left;
    width: 100%;
    text-align: center;
    font-size: 26rpx;
  }

  .criterion {
    float: left;
    width: calc(33.33% - 1px);
    text-align: center;
    background: #169bd542;
    margin-right: 1px;
    height: 40px;
    line-height: 40px;
    margin-bottom: 1px;
  }

  .skip {
    width: 100%;
    position: absolute;
    text-align: right;
    z-index: 2;
    display: flex;
    justify-content: flex-end;

    view {
      width: 100rpx;
      height: 50rpx;
      border-radius: 25rpx;
      background-color: #000000;
      opacity: 0.5;
      line-height: 50rpx;
      font-size: 24upx;
      color: #fff;
      text-align: center;
      margin: 20rpx;
    }
  }

  .img {
    width: 100%;
    height: 100vh;
  }

  image {
    width: 100%;
    height: 100vh;
  }

  .swiper {
    height: 100vh;
  }

  /deep/ .uni-navbar--border {
    border-bottom-color: #1977d2;
  }

  .tags {
    uni-tag {
      margin-right: 30rpx;
      background: #1977d2;
    }
  }

  /deep/ .uni-tag--success {
    background-color: #60a5e8;
    border-color: #60a5e8;
  }

  .title {
    margin: 20rpx 0;
  }

  .info {
    background: #eff8ff;
    padding: 30rpx;
    border-radius: 20rpx;
  }

  .tips {
    font-size: 12px;
    margin: 10px;
  }

  .filterBg {
    filter: grayscale(100%);
  }
</style>